package com.badger.generator.base.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.ModelAttribute;

import com.badger.generator.util.StringUtils;

/**
 * 基础controller
 * @author liqi
 */
public class BaseController {
    /** HttpServletRequest */
    private HttpServletRequest request;

    /** HttpServletResponse */
    private HttpServletResponse response;

    /**
     * 设置request和response
     * @param request
     * @param response
     */
    @ModelAttribute
    public void setReqAndRes(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
    }

    /**
     * 获取request对象
     * @return HttpServletRequest request
     */
    public HttpServletRequest getRequest() {
        return this.request;
    }

    /**
     * 获取response对象
     * 
     * @return HttpServletResponse response
     */
    public HttpServletResponse getResponse() {
        return this.response;
    }

    /**
     * 获取session对象
     * @return HttpSession session
     */
    public HttpSession getSession() {
        return this.request.getSession();
    }

    /**
     * 获取上下文对象
     * @return ServletContext servletContext
     */
    public ServletContext getServletContext() {
        return getSession().getServletContext();
    }

    /**
     * 获取请求的url
     * @return str
     */
    public String getRequestUrl() {
        return this.request.getRequestURI();
    }

    /**
     * 获取客户端IP
     * 
     * @return string
     */
    public String getIp() {
        String ip = this.request.getHeader("x-forwarded-for");
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = this.request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = this.request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = this.request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 得到Cookie的值, ecode不编码
     * @param cookieName
     * @return
     */
    public String getCookieValue(String cookieName) {
        return this.getCookieValue(cookieName, false);
    }

    /**
     * 得到Cookie的值
     * @param isDecoder ecode解码：true cookieValue 解码;false:cookieValue 不解码
     * @param cookieName cookie 名称
     * @return
     */
    public String getCookieValue(String cookieName, boolean isDecoder) {
        Cookie[] cookieList = this.request.getCookies();
        if (cookieList == null || cookieName == null) {
            return null;
        }
        String retValue = null;
        try {
            for (int i = 0; i < cookieList.length; i++) {
                if (cookieList[i].getName().equals(cookieName)) {
                    if (isDecoder) {
                        retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8");
                    } else {
                        retValue = cookieList[i].getValue();
                    }
                    break;
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return retValue;
    }

    /**
     * 设置Cookie的值 不设置生效时间默认浏览器关闭即失效,也不编码
     * @param cookieName
     * @param cookieValue
     */
    public void setCookie(String cookieName, String cookieValue) {
        this.setCookie(cookieName, cookieValue, -1);
    }

    /**
     * 设置Cookie的值 不设置生效时间默认浏览器关闭即失效,也不编码
     * @param cookieName cookie name
     * @param cookieValue cookie value
     * @param cookieMaxTime cookie 超时时间
     */
    public void setCookie(String cookieName, String cookieValue, int cookieMaxTime) {
        this.doSetCookie(cookieName, cookieValue, cookieMaxTime, false);
    }

    /**
     * 删除Cookie带cookie域名
     * @param cookieName
     */
    public void deleteCookie(String cookieName) {
        this.doSetCookie(cookieName, "", -1, false);
    }

    /**
     * 设置Cookie的值 在指定时间内生效，cookieValue是否进行Encode编码
     * @param cookieName
     * @param cookieValue
     * @param cookieMaxTime
     * @param isEncode   ecode编码：true cookieValue 编码;false:cookieValue 不编码
     */
    public void doSetCookie(String cookieName, String cookieValue, int cookieMaxTime, boolean isEncode) {
        try {
            if (cookieValue == null) {
                cookieValue = "";
            } else if (isEncode) {
                cookieValue = URLEncoder.encode(cookieValue, "utf-8");
            }
            Cookie cookie = new Cookie(cookieName, cookieValue);
            if (cookieMaxTime > 0) {
                cookie.setMaxAge(cookieMaxTime);
            }
            if (null != this.request) {
                // 设置域名的cookie
                String domainName = this.getDomainName();
                if (!"localhost".equals(domainName)) {
                    cookie.setDomain(domainName);
                }
            }
            cookie.setPath("/");
            this.response.addCookie(cookie);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 得到cookie的域名
     */
    public String getDomainName() {
        String domainName = "";
        String url = this.getRequestUrl();
        if (!StringUtils.isEmpty(url)) {
            url = url.toLowerCase().substring(7);
            final int end = url.indexOf("/");
            url = url.substring(0, end);
            final String[] domains = url.split("\\.");
            int len = domains.length;
            if (len > 3) {
                // www.xxx.com.cn
                domainName = "." + domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1];
            } else if (len <= 3 && len > 1) {
                // xxx.com or xxx.cn
                domainName = "." + domains[len - 2] + "." + domains[len - 1];
            } else {
                domainName = url;
            }
        }
        if (!StringUtils.isEmpty(domainName) && domainName.indexOf(":") > 0) {
            String[] ary = domainName.split("\\:");
            domainName = ary[0];
        }
        return domainName;
    }
}
